<template>
  <Drawer
    v-model:show="visible"
    type="confirm"
    :title="$t('Appliance.LearningProgram.Presetting.Modal.Title')"
    :desc="$t('Appliance.LearningProgram.Presetting.Modal.Content')"
    :cancel-text="$t('Appliance.LearningProgram.Presetting.Modal.Cancel.Text')"
    @confirm="confirmPresetting"
  >
    <view class="presetting-cards">
      <view v-for="option in PresettingOptions" :key="option.key" class="setting-card">
        <view class="body">
          <view class="title">{{ option.title }}</view>
          <view class="desc">{{ option.desc }}</view>
        </view>
        <view class="aside">
          <switch
            color="#108ee9"
            :checked="presettingForm[option.key]"
            @change="togglePresetting(option.key, option)"
          />
        </view>
      </view>
    </view>
  </Drawer>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import Drawer from '@/common/drawer.vue'
import {
  PresettingCleaning,
  PresettingDrying,
  PresettingDuration,
  PresettingKeys,
} from '@/controller/Dishwasher/Learning/constants'
import type { DishwasherController } from '@/controller/Dishwasher/definition'
import { setSetting } from '@/api/appliance'
import { cloneDeep } from 'lodash'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'

const props = defineProps<{
  show: boolean
  control: DishwasherController.Control
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
  (e: 'confirm'): void
}>()

const i18n = useI18n()
const visible = computed({
  get() {
    return props.show
  },
  set(show) {
    emit('update:show', show)
    !show && emit('close')
  },
})

const PresettingOptions = [
  {
    title: i18n.t('Appliance.LearningProgram.Presetting.Cleaning.Title'),
    desc: i18n.t('Appliance.LearningProgram.Presetting.Cleaning.Desc'),
    key: PresettingCleaning,
  },
  {
    title: i18n.t('Appliance.LearningProgram.Presetting.Drying.Title'),
    desc: i18n.t('Appliance.LearningProgram.Presetting.Drying.Desc'),
    key: PresettingDrying,
  },
  {
    title: i18n.t('Appliance.LearningProgram.Presetting.Duration.Title'),
    desc: i18n.t('Appliance.LearningProgram.Presetting.Duration.Desc'),
    key: PresettingDuration,
  },
]

/**
 * 勾选框表单
 */
let previousPresetting = getPresettingForm() // 记录上一次的预设置 用于过滤优化未修改的接口调用
const presettingForm = ref(getPresettingForm())
watch(
  () => props.show,
  (show) => {
    if (show) {
      previousPresetting = getPresettingForm()
      presettingForm.value = getPresettingForm()
    }
  }
)
function getPresettingForm() {
  return cloneDeep(props.control.store.presetting)
}
function togglePresetting(key: string, option: unknown) {
  presettingForm.value[key] = !presettingForm.value[key]
  // console.error(presettingForm)
}

async function confirmPresetting() {
  safeTrack(() => {
    type TrackData = {
      setting_key: unknown
      setting_value: unknown
    }
    const trackData: TrackData = {
      setting_key: [],
      setting_value: [],
    }
    trackData.setting_key = Object.keys(presettingForm.value)
    trackData.setting_value = Object.values(presettingForm.value)

    trackEvent('applince_setting', trackData, TrackType.ApplianceDetail)
  })
  try {
    const haId = props.control.store._datasource.haId
    const tasks = Object.entries(presettingForm.value).reduce<ReturnType<typeof setSetting>[]>((task, [key, value]) => {
      if (previousPresetting[key] !== value) {
        task.push(setSetting(haId, key, value))
      }
      return task
    }, [])
    await Promise.all(tasks)
  } catch (e) {
    console.error(e)
    uni.showToast({
      title: i18n.t('Appliance.LearningProgram.Presetting.SubmitError.Text'),
      icon: 'error',
    })
  }
}
</script>

<style scoped lang="less">
.presetting-cards {
  margin-top: 28rpx;
}
.setting-card {
  padding: 16rpx;
  background-color: #f4f4f6;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: flex-start;
  overflow: hidden;
  + .setting-card {
    margin-top: 24rpx;
  }
  .body {
    flex: 1;
  }
  .title {
    font-weight: 500;
    font-size: 32rpx;
    line-height: 44rpx;
    color: var(--dark-color);
  }
  .desc {
    font-weight: 400;
    font-size: 24rpx;
    line-height: 34rpx;
    color: rgba(var(--dark-vector), 0.8);
  }
  .aside {
    flex-shrink: 0;
  }
}
</style>
